package com.kuaimacode.kframework.web.service;

import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.service
 * @Description: created by IntelliJ IDEA
 * @date 2019-03-16 11:14
 */
@Service
public class IndexService {


    @Value("${img.upload.location.root}")
    private String uploadRootLocation;
    @Value("${img.upload.location.img}")
    private String imgUploadLocation;
    @Value("${project.domain}")
    private String domain;

    @Autowired
    private InviteService inviteService;
    @Autowired
    private SysParamService sysParamService;


    /**
     * 发送get请求,  下载图片
     **            路径
     * @return
     */
    public String httpGetImg(CloseableHttpClient client, String imgUrl,String flag) {


        // 发送get请求
        HttpGet request = new HttpGet(imgUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(50000).setConnectTimeout(50000).build();

        //设置请求头
        request.setHeader( "User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1" );

        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();

                InputStream in = entity.getContent();
                //String fileName = DateUtil.getNow(DateUtil.FORMAT_FOUR_MINUTE)+"_"+ flag +".png" ;
                String fileName = DateUtil.getNow(DateUtil.FORMAT_FOUR_MINUTE) +".png" ;
                FileUtils.copyInputStreamToFile(in, new File(uploadRootLocation + imgUploadLocation + fileName));
                //return uploadRootLocation + imgUploadLocation + fileName;
                return  fileName;

            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            request.releaseConnection();

        }
        return "";
    }
}
